import Vue from 'vue'
import App from './App';
import uView from '@/uni_modules/uview-ui'
Vue.use(uView)
// #ifdef  H5
// H5使用打开 此sdk
import TIM from 'tim-js-sdk';
// #endif

// #ifdef  MP-WEIXIN || APP-PLUS
// 小程序 app使用sdk
import TIM from 'tim-wx-sdk';
// #endif
import http from "./common/http/index";
import store from './store/index'
import {
  isJSON
} from './utils'
import './router.js'
import COS from './static/cos-wx-sdk-v5.js'
import {
  SDKAPPID
} from './static/utils/GenerateTestUserSig'
import TYPES from './utils/types'
Vue.config.productionTip = false

let ossDomain = '/static/images/kaluolin'
Vue.prototype.ossDomain = ossDomain
uni.ossDomain = ossDomain
App.mpType = 'app'
const tim = TIM.create({
  SDKAppID: SDKAPPID
})
tim.setLogLevel(1)
uni.$app = tim
uni.$app.registerPlugin({
  'cos-wx-sdk': COS
})
wx.store = store
wx.TIM = TIM

let $bus = new Vue()
uni.$SDKREADY = false

Vue.prototype.$http = http;
uni.$http = http;
Vue.prototype.TIM = TIM
Vue.prototype.$type = TYPES
Vue.prototype.$store = store
Vue.prototype.$bus = $bus
uni.$bus = $bus
tim.on(TIM.EVENT.SDK_READY, onReadyStateUpdate, this)
tim.on(TIM.EVENT.SDK_NOT_READY, onReadyStateUpdate, this)

tim.on(TIM.EVENT.KICKED_OUT, kickOut, this)
// 出错统一处理
tim.on(TIM.EVENT.ERROR, onError, this)

tim.on(TIM.EVENT.MESSAGE_RECEIVED, messageReceived, this)
tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, convListUpdate, this)
tim.on(TIM.EVENT.GROUP_LIST_UPDATED, groupListUpdate, this)
tim.on(TIM.EVENT.BLACKLIST_UPDATED, blackListUpdate, this)
tim.on(TIM.EVENT.NET_STATE_CHANGE, netStateChange, this)
tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, onMessageReadByPeer)

function onReadyStateUpdate({
  name
}) {
  const isSDKReady = (name === TIM.EVENT.SDK_READY)
  if (isSDKReady) {
    uni.$SDKREADY = true
    uni.$app.getMyProfile().then(res => {
      store.commit('updateMyInfo', res.data)
    })
    uni.$app.getBlacklist().then(res => {
      store.commit('setBlacklist', res.data)
    })
  }
  store.commit('setSdkReady', isSDKReady)
}

function kickOut(event) {
  store.dispatch('resetStore')
  wx.showToast({
    title: '你已被踢下线',
    icon: 'none',
    duration: 1500
  })
  setTimeout(() => {
    wx.reLaunch({
      url: '../login/main'
    })
  }, 500)
}

function onError(event) {
  // 网络错误不弹toast && sdk未初始化完全报错
  if (event.data.message && event.data.code && event.data.code !== 2800 && event.data.code !== 2999) {
    store.commit('showToast', {
      title: event.data.message,
      duration: 2000
    })
  }
}

function checkoutNetState(state) {
  switch (state) {
    case TIM.TYPES.NET_STATE_CONNECTED:
      return {
        title: '已接入网络', duration: 2000
      }
      case TIM.TYPES.NET_STATE_CONNECTING:
        return {
          title: '当前网络不稳定', duration: 2000
        }
        case TIM.TYPES.NET_STATE_DISCONNECTED:
          return {
            title: '当前网络不可用', duration: 2000
          }
          default:
            return ''
  }
}

function netStateChange(event) {
  console.log(event.data.state)
  store.commit('showToast', checkoutNetState(event.data.state))
}

function onMessageReadByPeer(event) {
  console.log(event)
}

function messageReceived(event) {
  console.log(event);
  for (let i = 0; i < event.data.length; i++) {
    let item = event.data[i]
    if (item.type === TYPES.MSG_GRP_TIP) {
      if (item.payload.operationType) {
        $bus.$emit('groupNameUpdate', item.payload)
      }
    }
  }
  store.dispatch('onMessageEvent', event)
}

function convListUpdate(event) {
  store.commit('updateAllConversation', event.data)
}

function groupListUpdate(event) {
  store.commit('updateGroupList', event.data)
}

function blackListUpdate(event) {
  store.commit('updateBlacklist', event.data)
}

// 获取系统信息
// let sysInfo = uni.getSystemInfo()
// store.commit('setSystemInfo', sysInfo)

function launchApp() {
  if ( plus.os.name == "Android" ) {
    plus.runtime.launchApplication( {pname:"com.kll.server"
      ,extra:{url:"http://www.html5plus.org"}}, function ( e ) {
        console.log(e);
        // alert( "Open system default browser failed: " + e.message );
    } );
  } else if ( plus.os.name == "iOS" ) {
    plus.runtime.launchApplication( {action:"http://www.html5plus.org"}, function ( e ) {
      console.log(e);
      // alert( "Open system default browser failed: " + e.message );
    } );
  }
}

const app = new Vue({
  store,
  ...App
});
app.$mount();
